package org.ben.birthday.twentybirthday.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.ben.birthday.twentybirthday.entity.User;
import org.ben.birthday.twentybirthday.utils.BaseController;
import org.ben.birthday.twentybirthday.utils.Msg;
import org.ben.birthday.twentybirthday.utils.Regular;
import org.ben.birthday.twentybirthday.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.repository.query.Param;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Ben
 * @Date: 2019/7/18 18:02
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户接口", value = "UserController")
public class UserController extends BaseController {


    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * 注册发送邮箱Controller
     * @param email
     * @param httpSession
     * @return Msg
     */
    @RequestMapping(value = "/registSendEmail",method=RequestMethod.POST)
    @ApiOperation(value = "用户注册验证码发送",notes = "邮箱不能为空", httpMethod = "POST", response = Msg.class)
    @ApiImplicitParam(paramType = "query", name = "email",
            value = "邮箱", required = true, dataType = "String")
    public Msg registSendEmailController(@Param("email")String email, HttpSession httpSession){
        Regular regular=new Regular();
        if (email==null||!regular.matchingEmail(email)){
            logger.error("邮箱为空或邮箱格式不对");
            return Msg.fail().add("error","邮箱为空或邮箱格式不对");
        }
        boolean judgment=iEmailSendService.registSelectEmailService(email);
      if (judgment){
          iEmailSendService.sendEmailService(httpSession,email,"regist","注册");
          return Msg.success().add("success","发送成功");
      }else{
          return Msg.fail().add("error","发送失败，该邮箱已被注册");
      }
    }

    /**
     * 用户注册Controller
     * @param user
     * @param bindingResult
     * @param verificationCode
     * @param httpSession
     * @param confirmPassword
     * @return Msg
     */
    @RequestMapping(value = "/regist",method = RequestMethod.POST)
    @ApiOperation(value = "用户注册",notes = "用户，验证码，确认密码不能为空", httpMethod = "POST", response = ModelAndView.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userName",
                    value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "password",
                    value = "密码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "phoneNumber",
                    value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "email",
                    value = "邮箱", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "encryptedProblem",
                    value = "密保问题", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "encryptedAnswer",
                    value = "密保答案", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "level",
                    value = "用户等级", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "userType",
                    value = "用户类别", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "verificationCode",
                    value = "注册验证码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "confirmPassword",
                    value = "确认密码", required = true, dataType = "String"),
    })
    public ModelAndView registController(@Valid User user, BindingResult bindingResult,@Param("verificationCode") String verificationCode, HttpSession httpSession, @Param("confirmPassword") String confirmPassword){
        ModelAndView modelAndView=new ModelAndView();
        if (bindingResult.hasErrors()) {
            Map<String, Object> map = new HashMap<>();
            List<FieldError> errors = bindingResult.getFieldErrors();
            logger.error("注册失败！");
            for (FieldError fieldError : errors) {
                logger.error("错误的字段名：" + fieldError.getField());
                logger.error("错误信息：" + fieldError.getDefaultMessage());
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
        modelAndView.setViewName("travel/userPage/travelRegist");
            return modelAndView;
    }
        if (verificationCode==null||confirmPassword==null){
            logger.error("验证码或确认的密码为空");
            modelAndView.setViewName("travel/userPage/travelRegist");
            return modelAndView;
        }
        if (user.getPassword().equals(confirmPassword)&&httpSession.getAttribute("registverificationCode").equals(verificationCode)){
        boolean judgment=iUserService.registService(user,httpSession);
        if (judgment){
            modelAndView.setViewName("travel/travelIndex");
            return modelAndView;
        }else {
            modelAndView.setViewName("travel/userPage/travelRegist");
            return modelAndView;
        }
        }
        logger.error("验证码错误或两次密码输入不符，请重新输入");
        modelAndView.setViewName("travel/userPage/travelRegist");
        return modelAndView;
    }

    /**
     * 用户名密码登录Controller
     * @param userName
     * @param password
     * @return ModelAndView
     */
    @RequestMapping(value = "/loginUserName",method = RequestMethod.POST)
    @ApiOperation(value = "用户账号密码登录",notes = "用户名，密码不能为空", httpMethod = "POST", response = ModelAndView.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userName",
                    value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "password",
                    value = "密码", required = true, dataType = "String"),
    })
    public ModelAndView loginUserNameController(@Param("userName") String userName,@Param("password") String password,HttpSession httpSession){
        ModelAndView modelAndView=new ModelAndView();
        if (userName==null||password==null){
            logger.error("用户名或密码为空，登录失败");
            modelAndView.setViewName("travel/userPage/travelLogin");
            return modelAndView;
        }else {
     Result result=iUserService.loginUserNameService(userName,password,httpSession);
        if (result.getCode()==5){
            modelAndView.setViewName("travel/travelIndex");
            return modelAndView;
        }else if (result.getCode()==0){
            modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
            return modelAndView;
        }else {
            modelAndView.setViewName("travel/userPage/travelLogin");
            return modelAndView;
        }
        }
    }

    /**
     * 邮箱验证码登录发送验证码Controller
     * @param email
     * @param httpSession
     * @return Msg
     */
    @RequestMapping(value = "/loginSendEmail",method = RequestMethod.POST)
    @ApiOperation(value = "用户邮箱验证码登录发送验证码",notes = "邮箱不能为空", httpMethod = "POST", response = Msg.class)
    @ApiImplicitParam(paramType = "query", name = "email",
                    value = "邮箱", required = true, dataType = "String")
    public Msg loginSendEmailController(@Param("email")String email, HttpSession httpSession){
        Regular regular=new Regular();
        if (email==null||!regular.matchingEmail(email)){
            logger.error("邮箱为空或邮箱格式不对");
            return Msg.fail().add("error","邮箱为空或邮箱格式不对");
        }
        boolean judgment=iEmailSendService.loginSelectEmailService(email);
       if (judgment){
        iEmailSendService.sendEmailService(httpSession,email,"login","登录");
        return Msg.success().add("success","发送成功");
    }else {
        return Msg.fail().add("error","该邮箱不存在，发送失败");
    }
}

    /**
     * 邮箱验证码登录loginController
     * @param userName
     * @param email
     * @param verificationCode
     * @param httpSession
     * @return ModelAndView
     */
    @RequestMapping(value = "/loginSendEmailController",method = RequestMethod.POST)
    @ApiOperation(value = "用户名，邮箱，验证码登录",notes = "用户名，密码不能为空", httpMethod = "POST", response = ModelAndView.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userName",
                    value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "email",
                    value = "邮箱", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "verificationCode",
                    value = "验证码", required = true, dataType = "String"),
    })
    public ModelAndView loginSendEmaiController(@Param("userName") String userName,@Param("email") String email,@Param("verificationCode") String verificationCode,HttpSession httpSession){
        ModelAndView modelAndView=new ModelAndView();
        if (userName==null||verificationCode==null||email==null){
            logger.error("用户名,验证码或者邮箱为空");
            modelAndView.setViewName("travel/userPage/travelLogin");
            return modelAndView;
        }else {
            Result result=iUserService.loginEmailService(httpSession,userName,email,verificationCode);
            if (result.getCode()==5){
                modelAndView.setViewName("travel/travelIndex");
                return modelAndView;
            }else if (result.getCode()==0){
                modelAndView.setViewName("travel/travelBackgroundPage/travelBackgroundIndex");
                return modelAndView;
            }else {
                modelAndView.setViewName("travel/userPage/travelLogin");
                return modelAndView;
            }
        }
    }

    /**
     * 更改密码邮箱验证updatePasswordSendEmailController
     * @param email
     * @param httpSession
     * @return Msg
     */
    @RequestMapping(value = "/updateSendEmail",method = RequestMethod.POST)
    @ApiOperation(value = "更改密码发送验证码",notes = "邮箱不能为空", httpMethod = "POST", response = Msg.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "email",
                    value = "邮箱", required = true, dataType = "String"),
    })
    public Msg updatePasswordSendEmailController(@Param("email") String email,HttpSession httpSession){
        Regular regular=new Regular();
        if (email==null||!regular.matchingEmail(email)){
            logger.error("邮箱为空或邮箱格式不对");
            return Msg.fail().add("error","邮箱为空或邮箱格式不对");
        }
        boolean judgment=iEmailSendService.loginSelectEmailService(email);
        if (judgment){
            iEmailSendService.sendEmailService(httpSession,email,"updatePassword","更改密码");
            return Msg.success().add("success","发送成功");
        }else {
            return Msg.fail().add("error","该邮箱不存在，发送失败");
        }
    }

    /**
     * 更改密码updatePasswordController
     * @param userName
     * @param usedPassword
     * @param updatePassword
     * @param httpSession
     * @param verificationCode
     * @return ModelAndView
     */
    @RequestMapping(value = "/updatePassword",method = RequestMethod.POST)
    @ApiOperation(value = "更改密码",notes = "用户名，原密码，更改的密码，邮箱，改密验证码不能为空", httpMethod = "POST", response = ModelAndView.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userName",
                    value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "usedPassword",
                    value = "原密码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "updatePassword",
                    value = "更改的密码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "email",
                    value = "邮箱", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "verificationCode",
                    value = "改密验证码", required = true, dataType = "String"),
    })
    public ModelAndView updatePasswordController(@Param("userName")String userName,@Param("email") String email,@Param("usedPassword") String usedPassword,@Param("updatePassword")String updatePassword,HttpSession httpSession,@Param("verificationCode")String verificationCode){
        ModelAndView modelAndView=new ModelAndView();
   if (userName==null||usedPassword==null||updatePassword==null||verificationCode==null||email==null){
       logger.error("用户名，原密码，更改的密码,验证码或者邮箱为空");
       modelAndView.setViewName("travel/userPage/travelUpdatePassword");
       return modelAndView;
   }
    boolean judgment=iUserService.updatePasswordService(userName,usedPassword,updatePassword,email,httpSession,verificationCode);
        if (judgment){
            modelAndView.setViewName("travel/userPage/travelLogin");
            return modelAndView;
        }else {
            modelAndView.setViewName("travel/userPage/travelUpdatePassword");
            return modelAndView;
        }
    }

    /**
     * 找回密码邮箱发送findPasswordSendEmailController
     * @param email
     * @param httpSession
     * @return Msg
     */
    @RequestMapping(value = "/findPasswordSendEmail",method = RequestMethod.POST)
    @ApiOperation(value = "找回密码发送验证码",notes = "邮箱不能为空", httpMethod = "POST", response = Msg.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "email",
                    value = "邮箱", required = true, dataType = "String"),
    })
    public Msg findPasswordSendEmailController(@Param("email") String email,HttpSession httpSession){
        Regular regular=new Regular();
        if (email==null||!regular.matchingEmail(email)){
            logger.error("邮箱为空或邮箱格式不对");
            return Msg.fail().add("error","邮箱为空或邮箱格式不对");
        }
        boolean judgment=iEmailSendService.loginSelectEmailService(email);
        if (judgment){
            iEmailSendService.sendEmailService(httpSession,email,"findPassword","找回密码");
            return Msg.success().add("success","发送成功");
        }else {
            return Msg.fail().add("error","该邮箱不存在，发送失败");
        }
    }



    /**
     * 根据用户名，密保问题，密保答案，找回密码findPasswordController
     * @param userName
     * @param encryptedProblem
     * @param encryptedAnswer
     * @param verificationCode
     * @param httpSession
     * @return ModelAndView
     */
    @RequestMapping(value = "/findPassword",method = RequestMethod.POST)
    @ApiOperation(value = "找回密码",notes = "用户名，邮箱，密保问题，密保答案，找回密码验证码不能为空", httpMethod = "POST", response = ModelAndView.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userName",
                    value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "email",
                    value = "邮箱", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "encryptedProblem",
                    value = "密保问题", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "encryptedAnswer",
                    value = "密保答案", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "verificationCode",
                    value = "找回密码验证码", required = true, dataType = "String"),
    })

    public ModelAndView findPasswordController(@Param("userName") String userName,@Param("email") String email,@Param("encryptedProblem") String encryptedProblem,@Param("encryptedAnswer") String encryptedAnswer,@Param("verificationCode") String verificationCode,HttpSession httpSession){
        ModelAndView modelAndView=new ModelAndView();
        if (userName==null||encryptedProblem==null||encryptedAnswer==null||verificationCode==null||email==null){
            logger.info("用户名，密保问题，密保答案或验证码为空，找回失败");
            modelAndView.setViewName("travel/userPage/travelFindPassword");
            return modelAndView;
        }else {
            boolean judgment=iUserService.findPasswordService(userName,email,httpSession,verificationCode,encryptedProblem,encryptedAnswer);
            if (judgment){
                modelAndView.setViewName("travel/userPage/travelFindPassword");
                return modelAndView;
            }else {
                modelAndView.setViewName("travel/userPage/travelFindPassword");
                return modelAndView;
            }
        }
    }
}
